﻿using Communication.StreamResource;

namespace Communication.Help;

/// <summary>
///     流资源帮助类，提供对IStreamResource类型的扩展方法
/// </summary>
public static class StreamResourceHelp
{
    /// <summary>
    ///     将字节数组写入流资源
    /// </summary>
    /// <param name="stream">流资源对象</param>
    /// <param name="data">要写入的字节数据</param>
    public static void Write(this IStreamResource stream, byte[] data)
    {
        // 调用流的Write方法，从0开始写入，写入长度为data数组长度
        stream.Write(data, 0, data.Length);
    }

    /// <summary>
    ///     从流资源中读取一个字节
    /// </summary>
    /// <param name="stream">流资源对象</param>
    /// <returns>读取到的字节值</returns>
    public static byte ReadByte(this IStreamResource stream)
    {
        // 创建一个长度为1的字节数组
        var result = new byte[1];
        // 从流中读取一个字节到result数组
        stream.Read(result, 0, 1);
        // 返回读取到的字节
        return result[0];
    }

    /// <summary>
    ///     从流资源中连续读取指定长度的数据到字节数组
    /// </summary>
    /// <param name="stream">流资源对象</param>
    /// <param name="data">存储读取数据的字节数组</param>
    /// <returns>实际读取的字节数</returns>
    public static int ContinuousRead(this IStreamResource stream, byte[] data)
    {
        // 调用重载方法，从0开始读取，读取长度为data数组长度
        return ContinuousRead(stream, data, 0, data.Length);
    }

    /// <summary>
    ///     从流资源中连续读取指定长度的数据到字节数组的指定位置
    /// </summary>
    /// <param name="stream">流资源对象</param>
    /// <param name="data">存储读取数据的字节数组</param>
    /// <param name="offset">数组中的起始位置</param>
    /// <param name="count">要读取的字节数</param>
    /// <returns>实际读取的字节数</returns>
    public static int ContinuousRead(this IStreamResource stream, byte[] data, int offset, int count)
    {
        var numBytesRead = 0;
        // 循环读取直到读取完指定的字节数
        while (numBytesRead != count)
        {
            // 累加每次读取的字节数
            numBytesRead += stream.Read(data, numBytesRead + offset, count - numBytesRead);
        }

        // 返回总共读取的字节数
        return numBytesRead;
    }

    /// <summary>
    ///     从流资源中连续读取指定长度的数据并返回新字节数组
    /// </summary>
    /// <param name="stream">流资源对象</param>
    /// <param name="count">要读取的字节数</param>
    /// <returns>包含读取数据的字节数组</returns>
    public static byte[] ContinuousRead(this IStreamResource stream, int count)
    {
        // 创建指定长度的字节数组
        var frameBytes = new byte[count];
        var numBytesRead = 0;
        // 循环读取直到读取完指定的字节数
        while (numBytesRead != count)
        {
            // 累加每次读取的字节数
            numBytesRead += stream.Read(frameBytes, numBytesRead, count - numBytesRead);
        }

        // 返回包含读取数据的字节数组
        return frameBytes;
    }
}